package com.team8.system.service.listener;

import com.team8.system.service.client.UploadClient;
import com.team8.system.service.service.SystemService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class XmlParseListener {

    @Autowired
    private SystemService systemService;

    @Autowired
    private UploadClient uploadClient;

    @RabbitListener(bindings = @QueueBinding(
                value = @Queue(
                        value = "as.xmlparse.queue",
                        durable = "true"
                ),     // 声明队列
                exchange = @Exchange(
                            value = "as.xmlparse.exchange",
                            ignoreDeclarationExceptions = "true",
                            type = ExchangeTypes.TOPIC
                ),
                key = {"#.#"}
            )
    )
    @Transactional
    public void listenXmlParse(String msg) throws Exception {
        if (msg == null) {            return;        }
        InputStream input = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(msg);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            long size = urlConnection.getContentLengthLong();
            input = urlConnection.getInputStream();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        if(input == null)          return;
        System.out.println("xmlParseListener   ->   " + msg);
        File file = new File(msg);
        if(msg.contains("BASE-APUE")){
            systemService.handleBASEAPUE(input);
        } else if(msg.contains("DFME-BLLS")) {
            systemService.handleDFMEBLLS(input);
        } else if(msg.contains("DFME-CKLS")) {
            systemService.handleDFMECKLS(input);
        }  else if(msg.contains("DFOE-DFDL")){
            systemService.handleDFOEDFDL(input);
        }
        String[] split = msg.split("/");
        uploadClient.updateXmlFileStatus(split[split.length - 1], "1");
    }
}
